#include "SCPlayer.h"
#include "Player.h"
#include <QTimer>

SCPlayer::SCPlayer(QWidget *parent)
	: QWidget(parent)
{

	ui.setupUi(this);

	connect(this, &SCPlayer::PlayerQuit_Signal, this, &SCPlayer::PlayerQuit);
	QTimer* timer = new QTimer();
	connect(timer, &QTimer::timeout, this, &SCPlayer::timeout);
	//timer->start(2000);
}

SCPlayer::~SCPlayer()
{
	connect(this, &SCPlayer::PlayerQuit_Signal, this, &SCPlayer::PlayerQuit);
}


void SCPlayer::PlayerButtonClicked(int index, QPushButton* btn)
{
	if (players[index])
	{
		btn->setText("CreatePlayer" + QString::number(index + 1));
		players[index]->Close();
		players[index]->deleteLater();
		players[index] = NULL;
	}
	else
	{
		btn->setText("DeletePlayer" + QString::number(index + 1));
		players[index] = new Player({ this, index, btn });
		players[index]->show();
	}
}


void SCPlayer::closeEvent(QCloseEvent *event)
{
	for (int i = 0; i < 3; i++)
	{
		if (!players[i]) continue;
		players[i]->Close();
		players[i]->deleteLater();
		players[i] = NULL;
	}
}


void SCPlayer::timeout()
{
	
	int randValue = (rand() % 3);
	if(randValue == 0)
		on_PlayerButton1_clicked();
	else if (randValue == 1)
		on_PlayerButton2_clicked();
	else if (randValue == 2)
		on_PlayerButton3_clicked();
}

QString SCPlayer::ConvertToTime(int ms, bool accurate)
{
	QTime n(0, 0, 0);
	QTime t;
	t = n.addMSecs(ms);
	if (accurate)
		return t.toString("h:mm:ss.zzz");
	else
		return t.toString("h:mm:ss");
}
